Parse.Cloud.define('saveQlGroup', async (req, res) => {
  const user = req.user
  const { name, gid, members = [] } = req.params
  if (!user) {
    return res.error('请先授权登录')
  }

  try {
    const account = await new Parse.Query('QlAccount').equalTo('user', user).first()
    if (!account) {
      return res.error('没有该用户')
    }

    const vip = account.get('vip')
    const endTime = account.get('endTime')
    const freeCount = account.get('freeCount')
    if (vip && endTime.getTime() < new Date().getTime()) {
      return res.error('vip已经过期')
    }

    if (!vip && account.get('freeCount') <= 0) {
      return res.error('试用次数已经用完')
    }

    const group = new Parse.Object('QlGroup')
    const currentGroup = await group.save({
      user,
      name,
      gid
    })

    await Parse.Object.saveAll(members.map(item => {
      const member = new Parse.Object('QlGroupMember')
      member.set('group', currentGroup)
      Object.keys(item).forEach(k => member.set(k, item[k]))
      return member
    }))

    if (!vip) {
      account.set('freeCount', freeCount - 1)
      await account.save()
    }

    res.success('ok')
  } catch (err) {
    console.log(err)
    res.error(err.message)
  }
})

